package com.nikmesoft.android.referendumfriend.activities;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.util.EntityUtils;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;

import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.ComponentName;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ResolveInfo;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.AsyncTask.Status;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;

import com.nikmesoft.android.referendumfriend.R;
import com.nikmesoft.android.referendumfriend.adapters.CropOptionAdapter;
import com.nikmesoft.android.referendumfriend.models.CropOption;
import com.nikmesoft.android.referendumfriend.service.ErrorCode;
import com.nikmesoft.android.referendumfriend.service.ForgotPass_handler;
import com.nikmesoft.android.referendumfriend.service.HttpFileUploader;
import com.nikmesoft.android.referendumfriend.service.ImageDownloader;
import com.nikmesoft.android.referendumfriend.service.LoginHandler;
import com.nikmesoft.android.referendumfriend.utils.CommonUtil;
import com.nikmesoft.android.referendumfriend.utils.Utilities;

public class Profile extends BaseActivity {
	EditText ed1, ed2, ed3,ed4;
	RadioGroup rdg;
	RadioButton rd_male,rd_female;
	private ImageView ivavatar;
	private EditText mDateDisplay;
	private Button mPickDate;
	private ProgressDialog dialog;
	private WSLoader loader;
	private int mYear;
	private int mMonth;
	private int mDay;
	private String fullname1="";
	private String username1="";
	private String birthday1="";
	private String email1="";
	private String gender1="";
	private String address1="";
	private String mobile1="";
	private String facebook1="";
	private boolean td=false;
	
	static final int DATE_DIALOG_ID1 = 0;

	private static final int TAKE_PHOTO_CODE = 100;
	private static final int PICK_PHOTO_CODE = 101;
	private static final int CROP_PHOTO_CODE = 102;
	private float AVATAR_SIZE = 100;
	private Bitmap selectedAvatar=null;
	private Uri mImageCaptureUri;

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.person);
		td=false;
		
		 dialog = new ProgressDialog(this);
			dialog.setMessage("Loading...Please wait...");
			
		ed1 = (EditText) findViewById(R.id.person_edfullname);
		ed1.setText(LoginHandler.result.getFullname());
		
		ed2 = (EditText) findViewById(R.id.person_eduser);
		ed2.setText(LoginHandler.result.getUsername());
		
		mDateDisplay = (EditText) findViewById(R.id.person_edbirthday);
		mDateDisplay.setText(LoginHandler.result.getBirthday());
		
		ed3 = (EditText) findViewById(R.id.person_edemail);
		ed3.setText(LoginHandler.result.getEmail());
		
		ed4 = (EditText) findViewById(R.id.profile_mobile);
		ed4.setText(LoginHandler.result.getMobile());
		
		
		rdg = (RadioGroup) findViewById(R.id.person_rdg);
		
		rd_male = (RadioButton) findViewById(R.id.person_rdmale);
		rd_female = (RadioButton) findViewById(R.id.person_rdfemale);
		if (LoginHandler.result.getGender()==0) rd_male.setChecked(true);
		else rd_female.setChecked(true);
		
		ivavatar = (ImageView) findViewById(R.id.ivavatar);
		if(LoginHandler.result.getBit()!=null)	ivavatar.setImageBitmap(LoginHandler.result.getBit());
		
		

		
		
		mPickDate = (Button) findViewById(R.id.person_btday);

		// add a click listener to the button
		mPickDate.setOnClickListener(new View.OnClickListener() {
			@SuppressWarnings("deprecation")
			public void onClick(View v) {
				showDialog(DATE_DIALOG_ID1);
			}
		});
	}


	public void callBack(View view) {
		finish();
	}
	public void update(String fullname,String username,String email,
			String birthday,String gender,String address, String mobile,String facebook)
	{
		
		LoginHandler.result.setFullname(fullname);
		LoginHandler.result.setUsername(username);
		LoginHandler.result.setBirthday(birthday);
		LoginHandler.result.setGender(Integer.parseInt(gender));
		LoginHandler.result.setAddress(address);
		LoginHandler.result.setMobile(mobile);
		LoginHandler.result.setEmail(email);
		LoginHandler.result.setFacebook(facebook);
	}
	public void callSave(View view) {
		String id=String.valueOf(LoginHandler.result.getId());
		fullname1=ed1.getText().toString().trim();
		String email=ed3.getText().toString().trim();
		username1=ed2.getText().toString().trim();
		birthday1=mDateDisplay.getText().toString().trim();
		email1=email;
		gender1="0";
		if (rd_male.isChecked()) gender1="0";
		else gender1="1";
		
		 address1="Default";
		 mobile1=ed4.getText().toString().trim();
		 facebook1="Default";
		
		
		
		if (loader == null || loader.isCancelled()
				|| loader.getStatus() == Status.FINISHED) {
			loader = new WSLoader();
			loader.execute(id,fullname1,email1,username1,birthday1,gender1,address1,mobile1,facebook1);
			
		}
	}
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case DATE_DIALOG_ID1:
			return new DatePickerDialog(this, mDateSetListener, 1991, 1,
					1);
		}
		return null;
	}

	private void updateDisplay() {
		mDateDisplay.setText(new StringBuilder()
				// Month is 0 based so add 1
				.append(mMonth + 1).append("/").append(mDay).append("/")
				.append(mYear).append(" "));
	}

	private DatePickerDialog.OnDateSetListener mDateSetListener = new DatePickerDialog.OnDateSetListener() {

		public void onDateSet(DatePicker view, int year, int monthOfYear,
				int dayOfMonth) {
			mYear = year;
			mMonth = monthOfYear;
			mDay = dayOfMonth;
			updateDisplay();
		}
	};
	public void pickFromGallery(View v) {

		Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
		photoPickerIntent.setType("image/*");
		startActivityForResult(photoPickerIntent, PICK_PHOTO_CODE);
	}

	public void takeAPhoto(View v) {

		Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
		mImageCaptureUri = Uri.fromFile(new File(Environment
				.getExternalStorageDirectory(),LoginHandler.result.getId()+ ".png"));

		takePictureIntent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT,
				mImageCaptureUri);
		takePictureIntent.putExtra("return-data", true);
		startActivityForResult(takePictureIntent, TAKE_PHOTO_CODE);
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {

		if (resultCode == RESULT_OK) {
			switch (requestCode) {
			case TAKE_PHOTO_CODE:
				doCrop();
				ivavatar.setImageBitmap(selectedAvatar);
				break;
			case PICK_PHOTO_CODE:
				mImageCaptureUri = data.getData();
				doCrop();
				ivavatar.setImageBitmap(selectedAvatar);
				break;
			case CROP_PHOTO_CODE:
				Bundle extras = data.getExtras();

				if (extras != null) {
					Bitmap bitmap = extras.getParcelable("data");
					ivavatar.setImageBitmap(bitmap);
					selectedAvatar = Utilities.getResizedBitmap(bitmap,
							(int) AVATAR_SIZE, (int) AVATAR_SIZE);
					td=true;
				}

				File f = new File(mImageCaptureUri.getPath());
				Log.d("PATH", mImageCaptureUri.getPath());
				if (f.exists()) {
					f.delete();
				}
				break;

			}

		}
	}

	private void doCrop() {
		final ArrayList<CropOption> cropOptions = new ArrayList<CropOption>();

		Intent intent = new Intent("com.android.camera.action.CROP");
		intent.setType("image/*");

		List<ResolveInfo> list = getPackageManager().queryIntentActivities(
				intent, 0);

		int size = list.size();

		if (size == 0) {
			// Utilities.toastNotify(this,
			// getString(R.string.crop_image_no_app));

			return;
		} else {
			intent.setData(mImageCaptureUri);

			intent.putExtra("outputX", 200);
			intent.putExtra("outputY", 200);
			intent.putExtra("aspectX", 1);
			intent.putExtra("aspectY", 1);
			intent.putExtra("scale", true);
			intent.putExtra("return-data", true);

			if (size == 1) {
				Intent i = new Intent(intent);
				ResolveInfo res = list.get(0);

				i.setComponent(new ComponentName(res.activityInfo.packageName,
						res.activityInfo.name));

				startActivityForResult(i, CROP_PHOTO_CODE);
			} else {
				for (ResolveInfo res : list) {
					final CropOption cropoption = new CropOption();

					cropoption.title = getPackageManager().getApplicationLabel(
							res.activityInfo.applicationInfo);
					cropoption.icon = getPackageManager().getApplicationIcon(
							res.activityInfo.applicationInfo);
					cropoption.appIntent = new Intent(intent);

					cropoption.appIntent
							.setComponent(new ComponentName(
									res.activityInfo.packageName,
									res.activityInfo.name));

					cropOptions.add(cropoption);
				}

				CropOptionAdapter adapter = new CropOptionAdapter(this,
						R.layout.cropoption_item, cropOptions);

				AlertDialog.Builder builder = new AlertDialog.Builder(this);
				builder.setTitle("test");
				builder.setAdapter(adapter,
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog, int item) {
								startActivityForResult(
										cropOptions.get(item).appIntent,
										CROP_PHOTO_CODE);
							}
						});

				builder.setOnCancelListener(new DialogInterface.OnCancelListener() {
					public void onCancel(DialogInterface dialog) {

						if (mImageCaptureUri != null) {
							getContentResolver().delete(mImageCaptureUri, null,
									null);
							mImageCaptureUri = null;
						}
					}
				});

				AlertDialog alert = builder.create();

				alert.show();
			}
		}
	}

	
	private String callWS(String id,String fullname,String email,String username,
			String birthday,String gender,String address, String mobile,String facebook) {
		String body = "<soapenv:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\">"
				+ "<soapenv:Header/><soapenv:Body>"
				+"<updateProfile soapenv:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\">"
				+"<UpdateProfileRequest xsi:type=\"rdf:UpdateProfileRequest\" xmlns:rdf=\"http://nikmesoft.com/apis/RDFServices/\">"
		        +"<id xsi:type=\"xsd:int\">"+id+"</id>"
		        +"<fullname xsi:type=\"xsd:string\">"+fullname+"</fullname>"
		        +"<email xsi:type=\"xsd:string\">"+email+"</email>"
		        +"<username xsi:type=\"xsd:string\">"+username+"</username>"
		        +"<birthday xsi:type=\"xsd:string\">"+birthday+"</birthday>"
		        +"<gender xsi:type=\"xsd:int\">"+gender+"</gender>"
		        +"<address xsi:type=\"xsd:string\">"+address+"</address>"
		        +"<mobile xsi:type=\"xsd:string\">"+mobile+"</mobile>"
		        +"<facebook xsi:type=\"xsd:string\">"+facebook+"</facebook>"
		        +"</UpdateProfileRequest>"
		        +"</updateProfile>"
		         +"</soapenv:Body>"
		         +"</soapenv:Envelope>";

		final DefaultHttpClient httpClient = new DefaultHttpClient();
		// request parameters
		HttpParams params = httpClient.getParams();
		HttpConnectionParams.setConnectionTimeout(params, 10000);
		HttpConnectionParams.setSoTimeout(params, 15000);
		// set parameter
		HttpProtocolParams.setUseExpectContinue(httpClient.getParams(), true);

		// POST the envelope
		HttpPost httppost = new HttpPost(
				"http://nikmesoft.com/apis/RDFServices/index.php");
		// add headers
		httppost.setHeader("SoapAction",
				"http://nikmesoft.com/apis/RDFServices/index.php/");
		httppost.setHeader("Content-Type", "text/xml; charset=utf-8");

		String responseString = "";
		try {

			// the entity holds the request
			HttpEntity entity = new StringEntity(body);
			httppost.setEntity(entity);

			// Response handler
			ResponseHandler<String> rh = new ResponseHandler<String>() {
				// invoked when client receives response
				public String handleResponse(HttpResponse response)
						throws ClientProtocolException, IOException {

					// get response entity
					HttpEntity entity = response.getEntity();

					// read the response as byte array
					StringBuffer out = new StringBuffer();
					byte[] b = EntityUtils.toByteArray(entity);

					// write the response byte array to a string buffer
					out.append(new String(b, 0, b.length));
					return out.toString();
				}
			};

			responseString = httpClient.execute(httppost, rh);

		} catch (Exception e) {
			Log.v("Exception", e.toString());
		}

		// close the connection
		httpClient.getConnectionManager().shutdown();
		Log.i("Webservice", responseString);
		return responseString;
	}

	private ErrorCode xmlParser(String strXml) {
		byte xmlBytes[] = strXml.getBytes();
		ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(
				xmlBytes);
		SAXParserFactory saxPF = SAXParserFactory.newInstance();
		SAXParser saxParser;
		try {
			saxParser = saxPF.newSAXParser();
			XMLReader xr = saxParser.getXMLReader();
			ForgotPass_handler handler = new ForgotPass_handler();
			xr.setContentHandler(handler);
			xr.parse(new InputSource(byteArrayInputStream));
			return handler.getResult();

		} catch (ParserConfigurationException ex) {
			ex.printStackTrace();
		} catch (SAXException ex) {
			ex.printStackTrace();
		} catch (IOException ex) {
			ex.printStackTrace();
		}
		return null;
	}

	private class WSLoader extends AsyncTask<String, Integer, ErrorCode> {

		@Override
		protected ErrorCode doInBackground(String... params) {
			
			ErrorCode err=xmlParser(callWS(params[0],params[1],params[2],params[3],params[4],
					params[5],params[6],params[7],params[8]));
			if (err==null && selectedAvatar!=null){
			String url = "http://nikmesoft.com/apis/RDFServices/avatarUploader.php";
			String filename = LoginHandler.result.getId()+".png";
			String s_data = "Nguyen The Linh";
			ByteArrayOutputStream bos = new ByteArrayOutputStream();
			selectedAvatar.compress(CompressFormat.PNG, 100, bos);
			byte[] data = bos.toByteArray();
			HttpFileUploader fileUploader = new HttpFileUploader(url, filename,
					data, s_data);
			fileUploader.doUpload();
			}
			
			return err;
		}

		@Override
		protected void onCancelled() {
			super.onCancelled();
		}

		@Override
		protected void onPostExecute(ErrorCode result) {
			super.onPostExecute(result);
			
			if (result!=null) toad(result.getErrorMsg());
			else 
				{			

			   update(fullname1, username1,email1, birthday1, gender1, address1, mobile1, facebook1);
			   if (td) LoginHandler.result.setBit(selectedAvatar);
			   finish();
				}
			dialog.dismiss();
		}

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			dialog.show();
		}

		@Override
		protected void onProgressUpdate(Integer... values) {
			super.onProgressUpdate(values);
		}

	}
	public void toad(String str){
		CommonUtil.toastNotify(this,str);
	}
}
